package com.foodlocker.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;



public class CommonFunction {

	public CommonFunction() {
		// TODO Auto-generated constructor stub
	}
	
	public  static void   alert(Context context,String title,String message) {
	    Dialog dialog = new AlertDialog.Builder(context).setTitle(title)
	            .setMessage(message)
	            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int which) {
	                   
	                }
	            }).create();
	    dialog.show();
	}
	
	
	//根据boxID号，生成开箱指令 ，放【0】行。   检查继电器状态放【1】行，检查输入状态指令放【2】行。关闭所有输出放【3】
		public static byte[][] generateOpenRelayBytes(int boxID,byte[] pcb_relay_state){
			byte[][] openRelayBytes= new byte[4][15];
			byte PCBID= (byte)(boxID/8+1);
			//byte RelayID=(byte)(boxID%8);
		//	byte  checkSum;
		
			for(int j=0;j<4;j++) {
		//	 int sum=0;
			openRelayBytes[j][0]=(byte)0X48;
			openRelayBytes[j][1]=(byte)0X3A;
			openRelayBytes[j][2]=PCBID;
			if (j==0) openRelayBytes[j][3]=(byte)0X57;
			else if(j==1)  openRelayBytes[j][3]=(byte)0X53;
			else if(j==2)  openRelayBytes[j][3]=(byte)0X52;
			else if (j==3) openRelayBytes[j][3]=(byte)0X57;
			for(int i=4;i<12;i++) {
				openRelayBytes[j][i]=(byte)0X00 ;
				}
		  if (j==0){  for(int i=4;i<12;i++) {
				openRelayBytes[j][i]=pcb_relay_state[i-4];
			//	System.out.println("PCBID--"+PCBID+"--STATICLOCKSsTATE---"+staticlocksState[PCBID][i-4]);
				
				}	 }
		  /*	   for(int i=0; i<12; i++){
			    	sum=sum+openRelayBytes[j][i];		    	
			    }
		      checkSum=(byte)(sum&0XFF); */
			openRelayBytes[j][12]=checkSum(openRelayBytes[j]);
			openRelayBytes[j][13]=(byte)0X45;
			openRelayBytes[j][14]=(byte)0X44;
	     //		for(int i=0;i<15;i++)  
		//		System.out.print(Integer.toHexString(openRelayBytes[j][i]&0XFF)+" ");
		//	 System.out.println(""); 
			}
			return openRelayBytes;
		}
	
		public static byte checkSum(byte[] data){
			 int sum=0;
			 byte  checkSum;
			   for(int i=0; i<12; i++){
			    	sum=sum+data[i];		    	
			    }
		      checkSum=(byte)(sum&0XFF);
		      return checkSum;
		}
		
		
		public static  String UniversalHttpPost(String  params[] ){
			
	        HttpResponse httpResponse;
	        HttpEntity httpEntity;
	        for(int i=0;i<params.length;i++)
	       	System.out.println("params["+i+"]="+params[i]);
	        NameValuePair pair1 =new BasicNameValuePair("PostCode", params[1]);
	        NameValuePair pair2 = new BasicNameValuePair("jsonData", params[2]);
	        NameValuePair pair3 =  new BasicNameValuePair("SID", params[3]);
	        NameValuePair pair4 = new BasicNameValuePair("Ssecret",params[4]);
	        NameValuePair pair5 = new BasicNameValuePair("courier_telnum", params[5]);
	        NameValuePair pair6 = new BasicNameValuePair("courier_secret",params[6]);
	        NameValuePair pair7 = new BasicNameValuePair("MID",params[7]);
	           NameValuePair pair8 = new BasicNameValuePair("Msecret",params[8]);
	        List<NameValuePair> pairList = new ArrayList<NameValuePair>();
	        pairList.add(pair1);
	        pairList.add(pair2);
	        pairList.add(pair3);
	        pairList.add(pair4);
	        pairList.add(pair5);
	        pairList.add(pair6);
	        pairList.add(pair7);
	        pairList.add(pair8);
	        InputStream  inputStream=null;
	        String result="";
	        try
	        {
	            HttpEntity requestHttpEntity = new UrlEncodedFormEntity(
	                    pairList);
	            // URL使用基本URL即可，其中不需要加参数
	          //    URL  baseURL= new URL( "http://192.168.1.104:8080/TestSQL/alessiomachineservlet");
	            HttpPost httpPost = new HttpPost( params[0]);
	            // 将请求体内容加入请求中
	            httpPost.setEntity(requestHttpEntity);
	            // 需要客户端对象来发送请求
	            HttpClient httpClient = new DefaultHttpClient();
	            // 发送请求
	             httpResponse = httpClient.execute(httpPost);
	             // 处理返回结果   
	             final int responseCode = httpResponse.getStatusLine().getStatusCode();  
	             if (responseCode == HttpStatus.SC_OK){
	            // 显示响应
	        	httpEntity=httpResponse.getEntity();
					 inputStream= httpEntity.getContent();
					BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
					String line=null;
					
					while((line=bufferedReader.readLine())!=null){
						result=result+line;	
					}
					result=result.trim();
					System.out.println(result);
	             }
	             else System.out.println("network error");
	        } catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println("can't connect to company's service");
				/*	本广播要发送给主界面，暂时不发送，
	             Intent intent = new Intent();//创建Intent对象  
	             intent.setAction(Constants.ACTION_TOMAIN);  
	       
	             intent.putExtra("data", "can't connect to company's service");  
	             sendBroadcast(intent);//发送广播  
	             */
				}finally{
					try {
						if(inputStream!=null) inputStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}   
	             
	             
	            
			   return result;
		   }
		
		 public static boolean isNumeric(String str){ 
			   for (int i = str.length();--i>=0;){ 
			   if (!Character.isDigit(str.charAt(i))){
			   return false; 
			   } 
			   }
			   return true; 
			   } 
}
